from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import io, re, json, datetime, os
from order.models import *
from user.models import *
from room.models import *
from .models import *

# Create your views here.
@csrf_exempt
def submit_complaint(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            complaint = Complaint()
            uid = User.objects.get(username=username).id
            rid = data_json.get('rid', 0)
            complaint.uid = uid
            complaint.rid = rid
            complaint.worker = data_json.get('worker', 0)
            complaint.info = data_json.get('info', "")
            complaint.starValue = data_json.get('starValue', 0)
            complaint.save()
            return JsonResponse({'errno': 0, 'msg': "评价提交成功"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})



@csrf_exempt
def search_complaints(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            res = []
            for complaint in Complaint.objects.all():
                res.append(complaint.get_info())
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': res})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def lookup_complaint(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
                return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            cpid = data_json.get('cpid', 0)
            user = User.objects.get(username=username)
            if Complaint.objects.filter(id=cpid).exists():
                complaint = Complaint.objects.get(id=cpid)
                if(complaint.uid == user.id or user.admin):
                    return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': complaint.get_info()})
                else:
                    return JsonResponse({'errno': 1004, 'msg': "用户登录信息错误"})
            else:
                return JsonResponse({'errno': 1003, 'msg': "房间不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})